package com.example.blogdemo

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.compose.setContent
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.ComposeView
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import java.lang.reflect.ParameterizedType

abstract class ComposeUiActivity<VM : BaseViewModel> : androidx.activity.ComponentActivity() {
    private val parameterizedType = javaClass.genericSuperclass as ParameterizedType
    private val vmClass = parameterizedType.actualTypeArguments[0] as Class<VM>
    protected lateinit var viewModel: VM
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        onDispense(savedInstanceState)
        setContent {
            MacawsTheme { pageContent() }
        }
    }

    @Composable
    abstract fun pageContent()

    open fun onDispense(savedInstanceState: Bundle?) {
        viewModel = getVM(vmClass, getVMFactory())
        initData()
    }

    open fun initData() {

    }


    open fun getVM(vmClass: Class<VM>, vmFactory: ViewModelProvider.Factory): VM {
        return ViewModelProvider(this, vmFactory)[vmClass] as VM
    }

    open fun getVMFactory(): ViewModelProvider.Factory {
        return defaultViewModelProviderFactory
    }
}

abstract class ComposeUIFragment <VM:BaseViewModel>: Fragment(){
    private val parameterizedType = javaClass.genericSuperclass as ParameterizedType
    private val vmClass = parameterizedType.actualTypeArguments[0] as Class<VM>
    protected lateinit var viewModel: VM

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        viewModel=getVM(vmClass,getVMFactory())
        return ComposeView(requireContext()).apply {
            setContent { MacawsTheme {
                pageContent()
            }}
        }
    }



    open fun getVM(vmClass: Class<VM>, vmFactory: ViewModelProvider.Factory): VM {
        return ViewModelProvider(this, vmFactory)[vmClass] as VM
    }

    open fun getVMFactory(): ViewModelProvider.Factory {
        return defaultViewModelProviderFactory
    }
    @Composable
    abstract fun pageContent()
}
class EmptyViwModel :BaseViewModel()